package com.springsecurity.services;

import com.springsecurity.data.constants.UserDetailsConstants;
import com.springsecurity.model.common.ModelObject;
import com.springsecurity.model.users.Account;
import com.springsecurity.model.users.User;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * Загрузка пользователя из БД
 * @author evob0413
 */
@Service
@Transactional(readOnly = true)
public class AccountService {

    @Autowired
    ModelObjectsService objectsService;
    
    public Account getAccountByLogin(String login) {
        List<ModelObject> users = objectsService.getObjectByObjectTypeAndName(
                UserDetailsConstants.TYPE_ACCOUNT, login);
        if (users == null || (users != null && users.isEmpty())) {
            return null;
        }
        //имя пользователя уникально
        ModelObject userObject = users.get(0);
        String email = (String)userObject.getParameter(UserDetailsConstants.ATTR_EMAIL);
        int passwordObjectId = (int)userObject.getParameter(UserDetailsConstants.ATTR_REF2PASSWORD);
        return new Account(userObject.getId(), login, getPasswordById(passwordObjectId), email);
    } 
    
    private String getPasswordById(int passwordObjectId) {
        ModelObject passwordObject = objectsService.getObjectByObjectId(passwordObjectId);
        return (String)passwordObject.getParameter(UserDetailsConstants.ATTR_PASSWORD);
    }

}
